
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class DiceController : MonoBehaviour
{
    public GameObject object1, object2, object3, object4, object5, object6;
    public string dicePoint;

    private Rigidbody m_rigidbody;
    public float torqueStrength = 10.0f; // 扭矩力的大小

    void Start()
    {
        m_rigidbody = GetComponent<Rigidbody>();
        transform.Rotate(Random.Range(0f, 360f), Random.Range(0f, 360f), Random.Range(0f, 360f));

        RollTheDice();

        Invoke("CheckPoint", 2);
    }

    public void RollTheDice()
    {
        // 生成一个随机的扭矩方向，使骰子滚动更自然
        Vector3 randomTorque = new Vector3(
            Random.Range(-1f, 1f),
            Random.Range(-1f, 1f),
            Random.Range(-1f, 1f)
        ).normalized * torqueStrength;

        // 使用AddRelativeTorque施加扭矩
        m_rigidbody.AddRelativeTorque(randomTorque, ForceMode.Impulse);
        m_rigidbody.AddRelativeForce(Vector3.forward*5,ForceMode.Acceleration);
    }

    void Update()
    {
        if (Input.anyKey)
        {
            SceneManager.LoadScene("DICE");
        }

        GameObject highestYObject = object1;   // 假設物件 1 的 Y 軸座標最高
        float highestY = object1.transform.position.y;

        // 檢查其它物件的Y軸座標，如果更高，則更新 highestYObject 和 highestY
        CheckAndUpdateYPosition(object2, ref highestYObject, ref highestY);
        CheckAndUpdateYPosition(object3, ref highestYObject, ref highestY);
        CheckAndUpdateYPosition(object4, ref highestYObject, ref highestY);
        CheckAndUpdateYPosition(object5, ref highestYObject, ref highestY);
        CheckAndUpdateYPosition(object6, ref highestYObject, ref highestY);

        dicePoint = highestYObject.name;   // 最後 highestYObject 就是 Y 軸座標最高的物件
    }

    void CheckAndUpdateYPosition(GameObject obj, ref GameObject highestYObject, ref float highestY)
    {
        if (obj.transform.position.y > highestY)
        {
            highestYObject = obj;
            highestY = obj.transform.position.y;
        }
    }

    void CheckPoint()
    {
        Debug.Log("點數：" + dicePoint);
    }
}

